import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Tools,DatePicker,Flex,ActionSheet,Icon ,Button,SearchBar,ActivityIndicator } from 'weaver-mobile';
import {getNow,toThousands,takeOutThousands} from '../../util/common'
import {Route, withRouter } from 'react-router-dom';
import QueueAnim from 'rc-queue-anim';
import { RouteLayout,ListPage,SearchAdvanced,DocumentTitle } from 'weaver-mobile-page';
import {openWorkFlow} from '../../util/pulic-func';
import {getTemplate} from '../../public/uiComponents/getTemplateInvoice';
import ToRememberDetailPage from './ToRememberDetailPage';
require('../../public/icon/iconfont');   //解决刷新页面后 无法获取到图标的问题。

const getLabel = Tools.getLabel;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

@withRouter
@inject ('accountBookStore')
@observer
class AccountBook extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            isReimbursed: 0, //1：报销   0：未报销
            isSelect:false, //是否点击  选择   --- 取消全选
            onRowSelect:[],  //是否选中 行 (复选框)
            allMoney:0.00   //选中的金额
        };
        this.sreenHeight = 0; 

        const {accountBookStore,location:{search}} = this.props;
        const {setDateParams,getBaseRoute} = accountBookStore;

        let now = getNow();
        setDateParams({
            year:now.year,
            month:now.month
        });
        
        //获取基础路由
        getBaseRoute(this);
    }

    static defaultProps = {
        prefixCls:"fna-accountBook"
    }

    componentWillMount() {

    }    

    componentDidMount() {
        const {accountBookStore} = this.props;
        const {initData} = accountBookStore;
        let now = getNow();

        let params = {
            dateQuery:now.year+'-'+now.month,
            isReimbursed:this.state.isReimbursed
        };
        this.sreenHeight = document.documentElement.clientHeight;
        initData(params);
        
    }

    componentWillUnmount(){
        const {accountBookStore} = this.props;
        const {clearData} = accountBookStore;
        clearData();
        ActionSheet.close();
    }


    render() {
        const { accountBookStore,prefixCls } = this.props;
        const { dateParams,reimbursable,reimbursed,search,remindList,allAccountData,getWorkflowList,nameQuery,setNameQuery,rememberGroup,mark,changeSearchValue,loading } = accountBookStore;
        const { toRememberDetailPageRoute,setToRememberDetailPageData,toRememberDetailPageData,getReimbursementReminderAll } = accountBookStore;
        const {form} = search;
        const {formParams} = form;

        return (
            <div className={`${prefixCls}`}>
                <DocumentTitle data={[{ match: /^\/accountBook/i, title: () => getLabel(516433,'记账本') }]} defaultTitle="" />
                <ActivityIndicator
                    toast
                    text="Loading..."
                    animating={loading}
                />
                <div className={`${prefixCls}-head`}>
                    <div className={`${prefixCls}-head-data`}>  
                        <DatePicker
                            mode="month"
                            onChange={this.getTime}
                        >
                            <span>{dateParams.year}{getLabel(445,'年')}{dateParams.month}{getLabel(6076,'月')}<Icon type={'down'} size={'xxs'} /></span>
                        </DatePicker>      
                    </div>

                    <Flex className={`${prefixCls}-head-flex`}>
                        <Flex.Item onClick={()=>{this.changeReimbursement(0)}}>
                            <div>{getLabel(516302,'未报销')}</div>
                            <div className="borderRight-line">{reimbursable}</div>
                            {!this.state.isReimbursed ? <div className="bg-sanjiaoUP"></div> : <div></div>}
                        </Flex.Item>
                        <Flex.Item onClick={()=>{this.changeReimbursement(1)}}>
                            <div>{getLabel(516304,'已报销')}</div>
                            <div>{reimbursed}</div>
                            {this.state.isReimbursed ? <div className="bg-sanjiaoUP"></div> : <div></div>}
                        </Flex.Item>
                    </Flex>
                </div>

                <QueueAnim duration={1000}>
                    <SearchBar
                        className="search-select"
                        placeholder={getLabel(517352,'请输入费用类型名称')}
                        value={nameQuery}
                        onChange={(val) => changeSearchValue(val)}
                        showExtraButton
                        extraButton={[{ key: 'advanced', show: <Icon key="filter-o" type="filter-o" /> }]}
                        onExtraButtonClick={(key) => { this.props.history.push(search.path) }}
                        onSubmit={(value)=>this.quickSearch(value)}
                        onClear={()=>{setNameQuery();this.quickSearch('')}}
                        key={'SearchBar'}
                    />

                    <SearchAdvanced
                        store={search}
                        buttonGroupData={this.getSearchFormBtn()} 
                    />

                    
                    {this.state.isReimbursed ? 
                        this.getOrderLayout(mark,rememberGroup)
                        : 
                        <div className={`${prefixCls}-select`}>
                            <QueueAnim duration={1000} type={['right']} animConfig={[
                                { opacity: [1, 0], translateX: [0, 50],display:'block' },
                                { display:'none' },
                            ]}>
                            {this.state.isSelect ? 
                                <div className={"accountBook-noSelect"}>
                                    <span>{getLabel(18609,'共')}<span>{this.state.onRowSelect.length}</span>{getLabel(18256,'条')}</span><i>{getLabel(358,'合计')}：</i><em>{toThousands(this.state.allMoney.toFixed(2))}</em>
                                    <div onClick={()=>{this.setState({
                                        isSelect : false,
                                        onRowSelect:[],
                                        allMoney:0,
                                    });remindList.selectNone();}}>
                                        {getLabel(387379,'取消全选')}
                                    </div>
                                </div> 
                                :
                                <div key={'accountBook'} className={"accountBook-isSelect"} onClick={()=>{this.setState({isSelect : true})}}>{getLabel(556,'全选')}</div>
                            } 
                            </QueueAnim>
                        </div>
                    }

                    <ListPage.Normal
                        className={this.state.isSelect ? 'fna-home-listPage fna-accountBook-listPage' : 'fna-home-listPage'}
                        style={{'maxHeight':(this.sreenHeight - 242),overflow:'auto','WebkitOverflowScrolling': 'touch'}}
                        showCheck={this.state.isSelect}
                        multipleCheck
                        withSwipeAction={true}
                        template={getTemplate({haveBorder:true})}
                        store={remindList}
                        onRowClick={(value)=>{ 
                            // if(this.state.isSelect){Bubble.error('请取消选择');return}
                            this.props.history.push(toRememberDetailPageRoute.path);
                            setToRememberDetailPageData({id:value.typeId,valueId:value.id,isReimbursed:this.state.isReimbursed}) 
                        }}
                        //getRowProps={this.getRowProps}
                        onRowSelect={(v,d)=>{this.onRowSelect(v,d)}}
                        swipeActionProps={{
                            style:{ backgroundColor: 'gray' },
                            autoClose:true,
                            right: this.state.isReimbursed ? [] : [{
                                text: getLabel(516582 ,'删除'),
                                onPress: (value) => this.doDelete(value),
                                style: { backgroundColor: '#F4333C', color: 'white' },
                            }] 
                            
                        }}

                        
                    />
                
                </QueueAnim>

                <div className={`${prefixCls}-footer`}>
                    {this.state.isReimbursed === 1 ?  
                        <Button type="primary"  style={{'border':0}} onClick={this.handleSubmit}>{getLabel(516431,'记一笔')}</Button>
                        :
                        (this.state.isSelect ?  
                            <div className="isReimbursed-isSelect-btn">
                                {remindList.isSelectedAll ? 
                                    <div onClick={()=>{remindList.selectNone();this.setState({onRowSelect:[],allMoney:0})}}><Icon type="check-circle" color={'#55b1f9'} size={'xs'}/>{getLabel('387379','取消全选')}</div> 
                                    : <div onClick={()=>{remindList.selectAll();this.onRowSelect([],remindList.data,true) }}><Icon type="uncheck" color="#ccc" size={'xs'}/>{getLabel('556','全选')}</div>}
                                <Button type="primary"  style={{'border':0}} onClick={this.handleSubmit}>{getLabel(516431,'记一笔')}</Button>
                                <Button type="primary"  style={{'border':0}} disabled={remindList.isSelectedAll == true ? false : (this.state.onRowSelect.length > 0 ? false : true)}  onClick={this.showReimbursementType}>{getLabel(383848,'发起报销')}</Button>
                            </div>
                            :
                            <div className="isReimbursed-btn">
                                <Button type="primary"  style={{'border':0}} onClick={this.handleSubmit}>{getLabel(516431,'记一笔')}</Button>
                                <Button type="primary"  style={{'border':0}} disabled={remindList.isSelectedAll == true ? false : (this.state.onRowSelect.length > 0 ? false : true)}  onClick={this.showReimbursementType}>{getLabel(383848,'发起报销')}</Button>
                            </div>
                        )
                    }
                </div>
               
                <Route
                    key={toRememberDetailPageRoute.id}
                    path={toRememberDetailPageRoute.path}
                    render={() => {
                        return (
                            <RouteLayout getContainer={() => document.getElementById("root")}>
                                <div
                                    key="crmListLayout"
                                    className="wm-route-layout"
                                >
                                    <ToRememberDetailPage toRememberDetailPageData={toRememberDetailPageData} refresh={()=>{
                                        let orderKey = '';
                                        for(let k in mark){
                                            if(mark[k] === 0 || mark[k] === 1){
                                                orderKey = k;
                                            }
                                        }

                                        let params = {
                                            dateQuery:dateParams.year+'-'+dateParams.month,
                                            isReimbursed:this.state.isReimbursed,
                                            ...formParams,
                                            nameQuery:nameQuery,
                                            orderKey:orderKey,
                                            order:mark[orderKey]
                                        }
                                        getReimbursementReminderAll(params);
                                    }} />
                                </div>
                            </RouteLayout>
                        )
                    }}
                /> 

            </div>
        )
    }

    //获取顶部 排序布局
    getOrderLayout = (markList,dataList) =>{

        return (
            <div className={'fna-accountBook-orderLayout-left'}>
                <Flex className={'fna-flex-img fna-flex-img-03'}>
                    {dataList.map( item => {
                        let _key = item.key;
                        //0 ：降序  箭头向下 从大到小
                        let _class = (markList[_key] === 0) ? 'sanjiao_down' : ( markList[_key] === 1 ? 'sanjiao_up' : 'sanjiao_none');

                        let conment = [];
                        {
                            conment = [
                                    <Flex.Item key={_key}  className={`fna-flex-img-item`} style={{position:'relative'}} 
                                        onClick={()=>{
                                            let  value = 0;
                                            if(markList[_key] != ''){
                                                value = markList[_key];
                                            };
                                            this.onClick({[_key]: (parseInt(value)+1)%2})}
                                        }
                                    >
                                        
                                        <div style={_class == 'sanjiao_none' ? {color:'#969BA6'} : {color:'#55B1F9'}} className={`fna-flex-img-item-text`} >
                                            {item.title} 
                                            {_class == 'sanjiao_none' ? 
                                                <Icon type={''} color={'#fff'}/> 
                                                : 
                                                (_class == 'sanjiao_up' ? 
                                                    <Icon type={'icon-up'} color={'#55B1F9'}/> 
                                                    :  
                                                    <Icon type={'icon-down'} color={'#55B1F9'} />
                                                ) 
                                            }
                                        </div>
                                    </Flex.Item>
                                ]
                        }
                        
                        return conment;
                    })}
                </Flex>
            </div>
        )
    }    

    getTime = (value) =>{
        const {accountBookStore} = this.props;
        const {setDateParams,getReimbursementReminderAll,search,nameQuery,mark} = accountBookStore;
        const {form} = search;
        const {formParams} = form;

        let y = value.split('-')[0];
        let m = value.split('-')[1];
        // console.log('mark',mark)
        setDateParams({
            year:y,
            month:m
        });

        let k = '';
        let v = '';
        for(let key in mark){
            if(mark[key] !== ''){
                k = key ;
                v = mark[key];
                break;
            }
        }

        let params = {
            dateQuery:value,
            isReimbursed:this.state.isReimbursed,
            ...formParams,
            nameQuery:nameQuery,
            orderKey:k,
            order:v
        };

        getReimbursementReminderAll(params);
    }

    getSearchFormBtn = ()=>{
        const { accountBookStore} = this.props;
        const {resetForm} = accountBookStore;
        const btns = [
          { key: 'reset', text: getLabel(2022,"重置"), onClick: () => {resetForm()}},
          { key: 'submit', text: getLabel(388113,"搜索"),onClick: () => {this.doSerch()}, type: 'primary',}
        ]
        return btns;
      }    

    //showMonth
    showReimbursementType = () =>{
        const {accountBookStore} = this.props;
        const {workflowSelect,wfInfo,creatWorkflow,getReimbursementReminderAll} = accountBookStore;

        let params = {
            ids: this.state.onRowSelect
        }
        
        const allMonth = workflowSelect;
        ActionSheet.showActionSheetWithOptions({
            options: allMonth,
            cancelButtonIndex: allMonth.length - 1,
            // destructiveButtonIndex: BUTTONS.length - 2,
            // title: '请选择月份',
            // message: '请选择月份',
            maskClosable: true,
            'data-seed': 'logId',
            wrapProps,
        },  
        (buttonIndex) => {
            const {accountBookStore} = this.props;
            const {nameQuery} = accountBookStore;

            if(buttonIndex != 'undefined' && buttonIndex != -1 && buttonIndex != allMonth.length - 1){
                let params = {
                    workflowId:workflowSelect[buttonIndex].id,
                    id:wfInfo.id
                }

                creatWorkflow(params,(value)=>{
                    openWorkFlow('view',value.requestId,()=>{
                        this.quickSearch(nameQuery)
                    });
                })
                
            }
                
        });     
        

          
    }

    onClick = (value) =>{
        const {accountBookStore} = this.props;
        const {setMark,search,getReimbursementReminderAll,mark,dateParams}  = accountBookStore;
        const {formParams} = search.form;

        let _obj = {};
        let temp_param = '';
        for(let key in mark){
            for(let k in value){
                if(key == k){
                    _obj[key] = value[k]; 
                    temp_param = key;
                }else{
                    _obj[key] = '';
                }
            }
        }
        setMark(_obj);

        getReimbursementReminderAll({
            dateQuery: dateParams.year+'-'+dateParams.month,
            ...formParams,
            // nameQuery:value,
            orderKey:temp_param,
            order:_obj[temp_param],
            isReimbursed:1
        })

    }

    //提交 普通搜索
    quickSearch = (value) =>{
        const {accountBookStore} = this.props;
        const {getReimbursementReminderAll,dateParams,search,setNameQuery,options,mark,resetList} = accountBookStore;
        const {form} = search;
        const {formParams} = form;

        value = value.trim();
        setNameQuery(value);

        this.setState({
            onRowSelect:[],
            allMoney:0,
        });
        resetList();

        for(let i=0;i<options.length;i++){
            if(options[i].showname == value){
                form.updateField('advQry_costType', options[i].key);
                break;
            }
        }
            
        let params = {
            dateQuery:dateParams.year+'-'+dateParams.month,
            isReimbursed:this.state.isReimbursed,
            ...form.formParams,
            nameQuery:value
        };

        let orderKey = '';
        for(let k in mark){
            if(mark[k] === 0 || mark[k] === 1){
                orderKey = k;
            }
        }

        params = Object.assign(params,{
            orderKey:orderKey,
            order:mark[orderKey]
        })

        getReimbursementReminderAll(params);
    }    

    //搜索
    doSerch = () =>{
        const {accountBookStore} = this.props;
        const {search,getReimbursementReminderAll,dateParams,setNameQuery,nameQuery,options,mark,resetList}  = accountBookStore;
        const {formParams} = search.form;

        this.setState({
            onRowSelect:[],
            allMoney:0,
        });
        resetList();

        //请求
        for(let i=0;i<options.length;i++){
            if(options[i].key == formParams.advQry_costType){
                setNameQuery(options[i].showname)
                break;
            }
        }
        let params = {
            dateQuery:dateParams.year+'-'+dateParams.month,
            isReimbursed:this.state.isReimbursed,
            ...formParams,
            nameQuery:accountBookStore.nameQuery
        };

        let orderKey = '';
        for(let k in mark){
            if(mark[k] === 0 || mark[k] === 1){
                orderKey = k;
            }
        }

        params = Object.assign(params,{
            orderKey:orderKey,
            order:mark[orderKey]
        })

        this.props.history.go(-1)
        getReimbursementReminderAll(params);

    }

    //记一笔
    handleSubmit = () =>{
        const {accountBookStore,history} = this.props;
        const {rememberChecked}  = accountBookStore;
        history.push('/remember')
    }

    //报销 切换
    changeReimbursement = (value) =>{
        const {accountBookStore} = this.props;
        const {getReimbursementReminderAll,dateParams,resetList,search,nameQuery,setMark} = accountBookStore;
        const {form} = search;
        const {formParams} = form;
        resetList();
        let _isReimbursement = value;

        this.setState({
            isReimbursed: _isReimbursement,
            isSelect : false,
            onRowSelect:[],
            allMoney:0,
        });

      

        //请求数据
        let params = {
            dateQuery:dateParams.year+'-'+dateParams.month,
            ...formParams,
            isReimbursed:value,
            nameQuery:nameQuery
        };

        if(value){
            params = Object.assign(params,{
                orderKey: 'time',
                order: 0
            })
        }else{
            setMark({},true)
        }
        getReimbursementReminderAll(params);
    }

    //选中 复选框
    onRowSelect = (value,datas,selectAll)=>{
        const {accountBookStore} = this.props;
        const {getWorkflowList,setWfInfo} = accountBookStore;

        let money = 0;
        let str = '';
        let id = '';
        for(let i=0;i<datas.length;i++){
            let oldMondy = takeOutThousands(datas[i].amount);
            money += parseFloat(oldMondy);
            if(i == 0){
                str = datas[i].typeId,
                id = datas[i].typeId+'_'+datas[i].id;
            }else {
                str += ','+datas[i].typeId;
                id += ','+datas[i].typeId+'_'+datas[i].id;
            }

            if(selectAll){
                value.push(datas[i].id);
            }

            
            
        }
        // allMoney
        this.setState({
            onRowSelect:value,
            allMoney:money
        });

        setWfInfo({id:id})
        getWorkflowList({ids:str})

    }

    //删除
    doDelete = (value) =>{
        const {accountBookStore} = this.props;
        const { doDeleteRemind,getReimbursementReminderAll,nameQuery,search,dateParams } = accountBookStore;
        const {form} = search;
        const {formParams} = form;

        let params = {
            id:value.id,
            typeId:value.typeId
        }       

        doDeleteRemind(params,()=>{
            getReimbursementReminderAll({
                dateQuery:dateParams.year+'-'+dateParams.month,
                isReimbursed:this.state.isReimbursed,
                nameQuery:nameQuery,
                ...formParams
            })
        });
        
        
        
    }

    

    
    

    
    

}

export default AccountBook;